package com.mxnet.chongjin.supoman.utils;

import android.os.CountDownTimer;
import android.os.Looper;
import android.text.TextUtils;

import com.android.tu.loadingdialog.LoadingDailog;
import com.mxnet.chongjin.supoman.R;
import com.mxnet.chongjin.supoman.config.Api;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

/**
 * author: Administrator
 * email: lcj270018655@163.com
 * date: 2018/5/24
 */

public class HttpUtils {
    public static String httpUrlConnetionGet(String urlStr) {
        try {
            //创建URL对象
            URL url = new URL(urlStr);//Get请求可以在Url中带参数： ①url + "?bookname=" + name;②url="http://www.baidu.com?name=zhang&pwd=123";
            //返回一个URLConnection对象，它表示到URL所引用的远程对象的连接
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            //在这里设置一些属性，详细见UrlConnection文档，HttpURLConnection是UrlConnection的子类
            //设置连接超时为5秒
            httpURLConnection.setConnectTimeout(5000);
            //设定请求方式(默认为get)
            httpURLConnection.setRequestMethod("GET");
            //建立到远程对象的实际连接
            httpURLConnection.connect();
            //返回打开连接读取的输入流，输入流转化为StringBuffer类型，这一套流程要记住，常用
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            String line = null;
            StringBuffer stringBuffer = new StringBuffer();
            while ((line = bufferedReader.readLine()) != null) {
                //转化为UTF-8的编码格式
                line = new String(line.getBytes("UTF-8"));
                stringBuffer.append(line);
            }
            bufferedReader.close();
            httpURLConnection.disconnect();
            return stringBuffer.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String httpUrlConnectionPost(String urlStr) {
        try {
            //创建URL对象
            URL url = new URL(urlStr);
            //返回一个URLConnection对象，它表示到URL所引用的远程对象的连接
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            //在这里设置一些属性，详细见UrlConnection文档，HttpURLConnection是UrlConnection的子类
            //设置连接超时为5秒
            httpURLConnection.setConnectTimeout(5000);
            //设定请求方式(默认为get)
            httpURLConnection.setRequestMethod("POST");
            // 设置是否向httpUrlConnection输出，因为这个是post请求，参数要放在
            // http正文内，因此需要设为true, 默认情况下是false;
            httpURLConnection.setDoOutput(true);
            // 设置是否从httpUrlConnection读入，默认情况下是true;
            httpURLConnection.setDoInput(true);
            // Post 请求不能使用缓存
            httpURLConnection.setUseCaches(false);


            //这边开始设置请求头
            // 设定传送的内容类型是可序列化的java对象(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
            httpURLConnection.setRequestProperty("Content-type", "application/x-java-serialized-object");
            //方法setRequestProperty(String key, String value)设置一般请求属性。
            // 连接，从上述url.openConnection()至此的配置必须要在connect之前完成，
            httpURLConnection.connect();

            //这边设置请内容
            //getOutputStream()里默认就有connect（）了，可以不用写上面的连接
            //接下来我们设置post的请求参数，可以是JSON数据，也可以是普通的数据类型
            OutputStream outputStream = httpURLConnection.getOutputStream();
            /**
             * JSON数据的请求
             * outputStream.write(stringJson.getBytes(), 0, stringJson.getBytes().length);
             * outputStream.close();
             * **/
            /**
             * 字符串数据的请求
             DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
             String content = "username=" + username + "&password=" + password;
             dataOutputStream.writeBytes(content);
             dataOutputStream.flush();
             dataOutputStream.close();
             * **/
            //读取返回的数据
            //返回打开连接读取的输入流，输入流转化为StringBuffer类型，这一套流程要记住，常用
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
            String line = null;
            StringBuffer stringBuffer = new StringBuffer();
            while ((line = bufferedReader.readLine()) != null) {
                //转化为UTF-8的编码格式
                line = new String(line.getBytes("UTF-8"));
                stringBuffer.append(line);
            }
            bufferedReader.close();
            httpURLConnection.disconnect();
            return stringBuffer.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Timer timer=new Timer();
    public static void controlCmd(String msg, String mac,String seq,ICallBack callBack ) {
        final String MAC = mac;
        final String SEQ = seq;
        final String MSG = msg;
        final ICallBack CALLBACK = callBack;
        final TimerTask timerTask=new TimerTask() {
            @Override
            public void run() {
                CALLBACK.onOverTime();
            }
        };
        timer.schedule(timerTask,4000);
        OkHttpUtils.get()
                .url(Api.URL_HEADER + Api.QUERY_CODE_New_STATUS)
                .addParams("macKey", MAC)
                .addParams("sequence", SEQ)
                .addParams("message", MSG)
                .addParams("messageReturn","73706D6EE05A2834FFFF9487E05A2834FFFFFFFFFFFF020101")
                .addParams("debugMode",Api.Debug_Mode.toString())
                .build()
                .execute(
                        new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                //ToastUtils.showToast(mContext, getResources().getString(R.string.net_fault));
                                CALLBACK.onError(e, id);
                                timerTask.cancel();
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                if (!TextUtils.isEmpty(response)) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        boolean success = jsonObject.optBoolean("success");
                                        if (success) {
                                            JSONObject data = jsonObject.optJSONObject("data");
                                            if (data != null) {
                                                String memo = data.optString("memo");
                                                String sequence = data.optString("sequence");
                                                if (!TextUtils.isEmpty(memo) && SEQ.toUpperCase().equals(sequence.toUpperCase())) {
                                                    if (memo.endsWith("01")) {   //成功
                                                        CALLBACK.onSuccess(SEQ);
                                                    } else if (memo.endsWith("00")) {
                                                        CALLBACK.onFail(SEQ, null);
                                                    }
                                                } else {
                                                    CALLBACK.onFail(SEQ, "无效的返回值");
                                                }
                                            } else {
                                                CALLBACK.onFail(SEQ, "无效的返回值");
                                            }
                                        } else {
                                            CALLBACK.onFail(SEQ, jsonObject.getString("msg"));
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        CALLBACK.onError(e, 0);
                                    }
                                } else {
                                    CALLBACK.onFail(SEQ, "无效的返回值");
                                }
                                timerTask.cancel();
                            }
                        }
                );


    }
}
